package dl.bukkit.myststus.configuration;

import dl.bukkit.myststus.MyStatus;
import dl.bukkit.myststus.configuration.imp.Config;
import dl.bukkit.myststus.library.ats.Configuration;
import dl.bukkit.myststus.loader.Loader;
import dl.bukkit.myststus.logger.Logger;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;

public class ConfigurationManager implements Loader {

    private static ConfigurationManager inst;

    public static File builderFile(String path) {
        return new File(inst.plugin.getDataFolder(), path);
    }

    public static void saveResource(String path) {
        Logger.consoleMessage("create file ", path);
        inst.plugin.saveResource(path, true);
    }

    private final List<IConfiguration> configurations = new LinkedList<>();

    private final MyStatus plugin;

    private ConfigurationManager(MyStatus plugin) {
        inst = this;
        this.plugin = plugin;
    }

    @Override
    public void onLoad() {
        register(Config.class);
        configurations.forEach(IConfiguration::saveConfig);
        configurations.forEach(IConfiguration::loadConfig);
    }

    private void register(Class<? extends IConfiguration> cls) {
        try {
            Constructor<? extends IConfiguration> constructor = cls.getDeclaredConstructor(String.class);
            constructor.setAccessible(true);
            Configuration annotation = cls.getAnnotation(Configuration.class);
            if (annotation == null) return;
            configurations.add(constructor.newInstance(annotation.path()));
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
